<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图-->
    <el-card>
      <!--添加按钮-->
      <el-row>
        <el-col>
          <el-button @click="showAddCateDialog" type="primary">添加分类</el-button>
        </el-col>
      </el-row>
      <!--表格-->
      <tree-table
        border
        :show-row-hover="false"
        index-text="#"
        show-index
        :expand-type="false"
        :selection-type="false"
        :data="cateList"
        :columns="columns">
        <!--是否有效-->
        <template slot="isOk" slot-scope="scope">
          <i v-if="scope.row.cat_deleted===true" class="el-icon-success" style="color: lightgreen"></i>
          <i v-if="scope.row.cat_deleted===false" class="el-icon-error" style="color: #ff0000"> </i>
        </template>
        <!--排序-->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag type="success" size="mini" v-if="scope.row.cat_level===1">二级</el-tag>
          <el-tag type="warning" size="mini" v-if="scope.row.cat_level===2">三级</el-tag>
        </template>
        <!--操作按钮-->
        <template slot="opt" slot-scope="scope">
          <el-button @click="showEditCateDialog(scope.row)" size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
          <el-button @click="deleteCate(scope.row)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
        </template>
      </tree-table>
      <!--分页-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!--添加分类对话框-->
    <el-dialog
      @close="addCateDialogClosed"
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%">
      <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="100px">
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类:">
          <el-cascader
            chagne
            clearable
            v-model="selectedKeys"
            :options="addCateList"
            :props="cascaderProps"
            @change="addCateListChanged"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addCateDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addCate">确 定</el-button>
  </span>
    </el-dialog>

    <!--编辑分类对话框-->
    <el-dialog
      @close="editCateDialogClosed"
      title="编辑分类"
      :visible.sync="editCateDialogVisible"
      width="50%">
      <el-form :model="editCateForm" :rules="editCateFormRules" ref="editCateFormRef" label-width="100px">
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editCateDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editCate">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "Cate",
  data() {
    return {
      //商品分类的数据列表
      cateList: [],
      //查询条件
      queryInfo: {
        pagenum: 1,
        pagesize: 10
      },
      //总数据条数
      total: 0,
      //为table指定列的定义
      columns: [
        {label: "分类名称", prop: "cat_name"},
        {label: "是否有效", type: "template", template: "isOk"},
        {label: "排序", type: "template", template: "order"},
        {label: "操作", type: "template", template: "opt"},
      ],
      //控制添加分类对话框的显示与隐藏
      addCateDialogVisible: false,
      //添加分类的表单数据对象
      addCateForm: {
        //分类父 ID
        cat_pid: 0,
        //分类名称
        cat_name: "",
        //分类层级`0`表示一级分类；`1`表示二级分类；`2`表示三级分类
        cat_level: 0
      },
      //添加分类的表单验证规则
      addCateFormRules: {
        cat_name: [
          {required: true, message: "请输入分类名称", trigger: "blur"}
        ],

      },
      //添加分类的数据列表
      addCateList: [],
      //指定级联选择器的配置对象
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
        checkStrictly: true
      },
      // 选中的父级分类的id数组
      selectedKeys: [],
      //控制编辑对话框的显示与隐藏
      editCateDialogVisible:false,
      //编辑分类的表单数据对象
      editCateForm:{
        //分类名称
        cat_name:"",
        // 分类id,携带在url中
        cat_id:"",
      },
      //编辑分类表单的验证规则
      editCateFormRules:{
        cat_name: [
          {required: true, message: "请输入分类名称", trigger: "blur"}
        ],
      },

    }
  },
  created() {
    this.getCateList();
  },
  methods: {
    //获取商品分类数据列表
    async getCateList() {
      const {data: res} = await this.$http.get(`categories`, {params: this.queryInfo})
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error("获取商品分类数据列表失败：" + res.meta.msg)
      this.cateList = res.data.result
      this.total = res.data.total
    },
    //监听pagesize改变事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    //监听pagenum改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },
    //点击按钮，展示添加分类对话框
    showAddCateDialog() {
      this.addCateDialogVisible = true
      //获取添加分类数据列表
      this.getAddCateList()

    },
    //获取添加分类数据列表
    async getAddCateList() {
      const {data: res} = await this.$http.get(`categories`, {
        params: {
          type: 2
        }
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error("获取商品分类数据列表失败：" + res.meta.msg)
      this.addCateList = res.data
    },
    //联级选择器改变
    addCateListChanged() {
      //如果selectedKeys数组中的长度>0，证明选中了父级分类
      if (this.selectedKeys.length > 0) {
        //父级分类的id
        this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        //为当前分类的等级赋值
        this.addCateForm.cat_level = this.selectedKeys.length
      }
      //反之，没有选中任何父级分类
      else {
        //父级分类的id
        this.addCateForm.cat_pid = 0
        //为当前分类的等级赋值
        this.addCateForm.cat_level = 0
      }
    },
    //点击按钮，提交添加分类表单
    addCate(){
      this.$refs.addCateFormRef.validate(async valid=>{
        if (!valid)return this.$message.warning("请完善表单数据")
        if(this.addCateForm.cat_level===0){
          const result = await this.$confirm('您还没有选择父级分类，此操作将会添加新的一级分类, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err)
          if (result !== "confirm") return this.$message.info("取消了添加分类")
        }
        const {data:res}=await this.$http.post("/categories",this.addCateForm)
        console.log(res)
        if(res.meta.status!==201)return this.message.error("添加分类失败："+res.meta.msg)
        this.$message.success("添加分类成功")
        this.addCateDialogVisible=false
        this.getCateList()
      })
    },
    //监听添加对话框的关闭事件,重置表单参数
    addCateDialogClosed(){
      this.$refs.addCateFormRef.resetFields()
      this.addCateForm={
        cat_level: 0,
        cat_pid: 0,
        cat_name: ""
      }
      this.selectedKeys=[]
    },
    //点击编辑，显示编辑对话框
    async showEditCateDialog(cate){
      this.editCateDialogVisible=true
      //根据 id 查询分类
      const cat_id=cate.cat_id
      const {data:res}=await this.$http.get(`categories/${cat_id}`)
      console.log(res)
      if(res.meta.status!==200)return this.$message.error("查询分类失败："+res.meta.msg)
      this.editCateForm.cat_name=res.data.cat_name
      this.editCateForm.cat_id=res.data.cat_id
    },
    //点击按钮，提交编辑表单
    editCate(){
      this.$refs.editCateFormRef.validate(async valid=>{
        if(!valid)return this.$message.warning("请完善表单信息")
        const {data:res}=await this.$http.put(`categories/${this.editCateForm.cat_id}`,this.editCateForm)
        console.log(res)
        if(res.meta.status!==200)return this.$message.error("更新失败："+res.meta.msg)
        this.$message.success("更新成功")
        this.editCateDialogVisible=false
        this.getCateList()
      })
    },
    //监听编辑对话框的关闭事件，重置表单参数
    editCateDialogClosed(){
      this.editCateForm={
        cat_name:"",
      }
    },
    //点击按钮，删除分类
    async deleteCate(cate){
      const result = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err=>err)
      const cat_id=cate.cat_id
      if (result !== "confirm") return this.$message.info("取消了添加分类")
      const {data:res} = await this.$http.delete(`categories/${cat_id}`)
      console.log(res)
      if(res.meta.status!==200) return this.$message.error("删除失败："+res.meta.msg)
      this.$message.success("删除成功")
      this.getCateList()
    },

  }
}
</script>

<style scoped>
.zk-table {
  margin-top: 15px;
}

.el-cascader {
  width: 100%;
}
</style>
